//获取基地址
axios.defaults.baseURL = "http://ajax-base-api-t.itheima.net";

//获取元素
const tb = document.querySelector('#tb')
const form = document.querySelector('#bookForm')


const rederbox = (params) => {
  console.log(params);
  axios.get('/api/getbooks' ,{params}).then(({ data: res }) => {
    const {data} = res
  const html = data.map(item => {
    return `
    <tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="#" data-id = ${item.id}>删除</a></td>
      </tr>
      `
  }).join('')
    tb.innerHTML = html
  })
}
rederbox()

//添加
form.addEventListener('click', function (e) {
  // console.log(e.target);
  e.preventDefault()
  if (e.target.dataset.name === 'tian') {
    const data = serialize(this, { hash: true })
  axios({
    url: '/api/addbook',
    method: 'POST',
    data
  }).then(({ data: res }) => {
    alert(res.msg)
    if(!res.status === 201) return
    this.reset()
    rederbox()
  })
 }
})

//删除
tb.addEventListener('click', function (e) {
  if (e.target.tagName === 'A') {
    const id = e.target.dataset.id
    axios({
      url: '/api/delbook',
      params : {id}
    }).then(({ data: res }) => {
      alert(res.msg)
      rederbox()
   })
  }
})

//筛选
form.addEventListener('click', function (e) {
  if (e.target.dataset.name === 'sai') {
    const data = serialize(this, { hash: true })
    rederbox(data)
  }
})
